package net.dgg.zz.production.receive.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.datapermission.service.DataPermissionAssocService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.entity.Node;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.FlowService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.dao.*;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 待接收service
 * <p>
 * @Package: net.dgg.zz.production.receive.service
 * </p>
 * <p>
 * @Title：ReceiveService
 * </p>
 * <p>
 * @description:
 * </p>
 * <p>
 * @author liulei
 * </p>
 * <p>
 * @date 2018年8月20日
 * </p>
 * <p>
 * @Company dgg
 * </p>
 */
@Service
public class ReceiveOrderService {

	@Autowired
	private ProductOrderDao productOrderDao;

	@Autowired
	private SessionManager sessionmanager;

	@Autowired
	private UserService userservice;

	@Autowired
	private SystemRecordService systemRecordService;
	@Autowired
	private CommonService commonService;

	/**
	 * 注册接口
	 */
	@Autowired
	private CommonMangerExtService commonMangerExtService;

	@Autowired
	private ProductTimeStatusDao productTimeStatusDao;

	@Autowired
	private ProductNodeFlowDao nodeFlowDao;

	@Autowired
	private ProductNodeDao productNodeDao;

	@Autowired
	private ProductNodeOperatingDao nodeOperatingDao;

	@Autowired
	private DataPermissionAssocService datapermissionassocservice;

	@Autowired
	private DesUtil desUtil;

	@Autowired
	private FlowService flowService;

	/**
	 * 查询所有待接收配列表
	 *
	 * @param param
	 * @return
	 */
	public List<Map> findAllWithPage(Map param) {
		UserEntity curentUser = sessionmanager.getCurrentUser();// 当前操作人
		param.put("userId", curentUser.getId());
		param.put("SC_TO_RECEIVE_FPDJS", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收
		param.put("SC_TO_RECEIVE_ZDDJS", ScProductConstant.SC_TO_RECEIVE_ZDDJS);//转单待接收
		param.put("SC_TO_RECEIVE_YJDJS", ScProductConstant.SC_TO_RECEIVE_YJDJS);//移交待接收
		param.put("SC_TO_RECEIVE_TDDJS", ScProductConstant.SC_TO_RECEIVE_TDDJS);//退回待接收
	 /*   DataAuthDTO dataAuthDTO = datapermissionassocservice.selectAuthToConfigureRturnOrgIds("ZZSC_WAIT_RECEIVE");
	    param.put("DeptIdList", dataAuthDTO.getOrgIds());*/
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
		if (null == param.get("orderColumn")) {
			param.put("orderDir", "desc");
			param.put("orderColumn", "t.update_time");
		}
		return productOrderDao.findWaitReceiveAllWithPage(param);
	}

	/**
	 * 接收订单
	 *
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public String receivedOrder(Map param) {
		UserEntity curentUser = sessionmanager.getCurrentUser();// 当前操作人
		Map map = this.commonMangerExtService.findOrg(curentUser.getOrgId());
		Long id = Long.parseLong(param.get("id").toString());
		ProductOrder order = productOrderDao.selectByPrimaryKey(id);
		if (!order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_FPDJS)
				&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_ZDDJS)
				&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_YJDJS)
				&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_TDDJS)) {// 判断当前订单状态是否改变
			return "接收失败,当前订单状态已改变";
		}
		if (null == map) {
			return "接收失败,系统参数异常,请联系管理员";
		}
		if(null==order.getNodeFlowId()) {
			return "未查询到"+order.getProductOrgName()+"流程节点配置信息";
		}
		if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
			if(!curentUser.getId().equals(order.getReceiverId())){
				return "您无权操作,当前操作人不是接收人";
			}
		} else {// 分配给负责人
			if(!curentUser.getId().equals(order.getProductUserId())){
				return "您无权操作,当前操作人不是接收人";
			}
		}
		List<Map> productNode = productNodeDao.queryNodeListByNodeFolwId(order.getNodeFlowId());
		if(null==productNode || productNode.size()==0) {
			return "未查询到"+order.getProductOrgName()+"流程节点配置信息";
		}
		order.setReceiverId(curentUser.getId());
		order.setReceiverName(curentUser.getRealName()+curentUser.getLoginName());
		order.setReceiverOrgId(curentUser.getOrgId());
		order.setReceiverOrgName(map.get("name").toString());
		order.setReceiveTime(new Date());
		order.setFlowUserId(curentUser.getId());
		order.setFlowUserName(curentUser.getRealName()+curentUser.getLoginName());
		order.setFlowUserOrgId(curentUser.getOrgId());
		order.setFlowUserOrgName(map.get("name").toString());
		order.setUpdaterId(curentUser.getId());
		order.setUpdaterName(curentUser.getRealName());
		order.setUpdaterOrgId(curentUser.getOrgId());
		order.setUpdaterOrgName(map.get("name").toString());
		order.setUpdateTime(new Date());
		Long operationgId = DggKeyWorker.nextId();//更新记录id
		order.setLatestEndUserId(curentUser.getId());
		order.setLatestEndUserName(curentUser.getRealName()+curentUser.getLoginName());
		order.setLatestEndNodeId(productNode.get(0).get("id").toString());
		order.setLatestEndNodeName(productNode.get(0).get("name").toString());
		order.setLatestEndNodeTime(new Date());
		order.setLatestNodeOperatingId(operationgId);
		order.setLatestFlowOperatingId(order.getNodeFlowId());
		order.setLatestEndUserOrgId(curentUser.getOrgId());
		order.setStatus(ScProductConstant.SC_ORDER_IN_PROCESS);
		productOrderDao.updateByPrimaryKey(order);

		//更新节点记录实体
		ProductNodeOperating operating = new ProductNodeOperating();
		operating.setId(operationgId);
		operating.setScProductOrderId(order.getId());
		operating.setScProductOrderNo(order.getScProductOrderNo());
		operating.setFlowUserId(curentUser.getId());
		operating.setFlowUserName(curentUser.getRealName());
		operating.setFlowOrgId(curentUser.getOrgId());
		operating.setFlowOrgName(map.get("name").toString());
		operating.setOrderStatus(order.getStatus());
		operating.setNodeId(productNode.get(0).get("id").toString());
		operating.setNodeName(productNode.get(0).get("name").toString());
		operating.setRemarksType(1);
		ProductNodeFlow f =nodeFlowDao.selectByPrimaryKey(order.getNodeFlowId());
		operating.setNodeProcessTimeType(f.getIsnaturalorworkday()==null?null:f.getIsnaturalorworkday().toString());
		operating.setNodeOpetateTime(new Date());
		operating.setCreaterId(curentUser.getId());
		operating.setCreaterName(curentUser.getRealName()+curentUser.getLoginName());
		operating.setCreateTime(new Date());
		operating.setCreaterOrgId(curentUser.getOrgId());
		operating.setCreaterOrgName(map.get("name").toString());
		 //超期计算
		 ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
		 if(null!=timestatus && null!=timestatus.getReceiveEndTime()){
			 	int i=DateUtils.compare_date(new Date(),timestatus.getReceiveEndTime());
			 if(i>=1){
				 timestatus.setReceiveTimeStatus(ScProductConstant.TIME_OUT);
				 operating.setNodeTimeStatus(ScProductConstant.TIME_OUT);
			 }else {
				 timestatus.setReceiveTimeStatus(timestatus.getReceiveTimeStatus());
				 operating.setNodeTimeStatus(ScProductConstant.NORMAL);
			 }
			 operating.setNodeStartTime(timestatus.getReceiveStartTime());
			 operating.setNodeEndTime(timestatus.getReceiveEndTime());

			 productTimeStatusDao.updateTimeOutStatus(timestatus);
		 }
		 nodeOperatingDao.insertProductNodeOperating(operating);
		// 插入操作记录
		SystemRecord record = new SystemRecord();
		record.setId(DggKeyWorker.nextId());// id
		record.setSource("2");
		record.setWorkTableName("zzsc_product_order");
		record.setWorkId(order.getId());
		record.setWorkNo(order.getScProductOrderNo());
		record.setOperateType("22");
		record.setRemarks("订单接单");
		systemRecordService.save(record);
		//通过MQ推送消息到UC
		CustomerRecord customerRecord = new CustomerRecord();
		customerRecord.setCustomerId(order.getCustomerId());
		customerRecord.setTableName("zzsc_product_order");
		customerRecord.setTableId(order.getId());
		customerRecord.setTableNo(order.getScProductOrderNo());
		customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE20);
		customerRecord.setCreaterId(curentUser.getId());
		customerRecord.setContent("接收订单");
		MQMessageSendUtil.ucMessageSend(customerRecord);
		//提交之后，将订单信息同步到企大顺生产中心
		MQMessageSendUtil.qdsMessageSend(order, null,  curentUser);
		return "success";
	}

	/**
	 * 订单退回
	 *
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public String goBack(Map param) {
		Long id = Long.parseLong(param.get("id").toString());
		ProductOrder order = productOrderDao.selectByPrimaryKey(id);
		UserEntity userEntity = sessionmanager.getCurrentUser();// 当前操作人
		Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());
		if (!order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_FPDJS)
				&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_ZDDJS)
				&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_YJDJS)
				&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_TDDJS)) {// 如果当前状态不是分配待接收、转单待接收、转交待接收、移交待接收
			return "当前订单状态已改变，不能进行退单";
		}
		if (null != map) {
			Long uId = null;//退回前流程人员id

			String uName = "";//退回前流程人员name

			Long deptId = null;//退回前流程人员部门id

			String deptName = "";//退回前流程人员部门
			if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
				uId = order.getReceiverId();//接单人id
				uName = order.getReceiverName();//接单人
				deptId = order.getReceiverOrgId();
				deptName = order.getReceiverOrgName();
			} else {
				uId = order.getProductUserId();//负责人id
				uName = order.getProductUserName();//负责人
				deptId = order.getProductOrgId();
				deptName = order.getProductOrgName();
			}
			UserEntity user = new UserEntity();
			int commonStatus = 0;//用于区分发送消息的模板
			if (ScProductConstant.SC_TO_RECEIVE_FPDJS.equals(order.getStatus())) {// 如果是分配待接收状态
				commonStatus = 1;//分配退回
				Long allotUserId = order.getAllotUserId();//获取分配人员Id
				user = userservice.findUserById(allotUserId);
				param.put("status", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);// 退回待分配状态原有的数据清空
				param.put("receiverId", null);
				param.put("receiverName", null);
				param.put("receiverOrgId", null);
				param.put("receiverOrgName", null);
				param.put("productUserId", null);
				param.put("productUserName", null);
				param.put("productUserOrgId", null);
				param.put("productUserOrgName", null);
			} else {
				Long waitingReceiverId = order.getWaitingReceiverId();
				user = userservice.findUserById(waitingReceiverId);
				Map receicveMap = this.commonMangerExtService.findOrg(userEntity.getOrgId());
				param.put("status", ScProductConstant.SC_TO_RECEIVE_TDDJS);// 退回待接收
				if (null == waitingReceiverId) {
					return "退回失败,未查询到订单原流程人员";
				}
				if (null == user) {
					return "退回失败,未查询到订单原流程人员";
				}
				if (ScProductConstant.SC_TO_RECEIVE_ZDDJS.equals(order.getStatus())) {// 如果是转单待接收状态不做状态改变
					param.put("originCode", ScProductConstant.ORDER_SOURCE_SLIP_RETURN);//资源来源转单
					commonStatus = 2;
				}
				if (ScProductConstant.SC_TO_RECEIVE_YJDJS.equals(order.getStatus())) {// 如果是移交待接收状态不做状态改变
					param.put("originCode", ScProductConstant.ORDER_SOURCE_TRANSFER_RETURN);//资源来源移交
					commonStatus = 3;
				}
				// 如果是退回待接收进行退回就不改变来源方式
				if (ScProductConstant.SC_TO_RECEIVE_TDDJS.equals(order.getStatus())) {
					param.put("originCode", order.getOriginCode());
					commonStatus = 2;
				}

				map.put("status", order.getStatus());//保存原状态
				if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
					if (!userEntity.getId().equals(order.getReceiverId())) {
						return "您无权操作,当前操作人不是接收人";
					}
					param.put("receiverId", user.getId());
					param.put("receiverName", user.getRealName());
					param.put("receiverOrgId", receicveMap.get("id"));
					param.put("receiverOrgName", receicveMap.get("name"));
				} else {// 分配给负责人
					if (!userEntity.getId().equals(order.getProductUserId())) {
						return "您无权操作,当前操作人不是接收人";
					}
					param.put("receiverId", user.getId());
					param.put("receiverName", user.getRealName());
					param.put("receiverOrgId", receicveMap.get("id"));
					param.put("receiverOrgName", receicveMap.get("name"));
					param.put("productUserId", user.getId());
					param.put("productUserName", user.getRealName());
					param.put("productUserOrgId", receicveMap.get("id"));
					param.put("productUserOrgName", receicveMap.get("name"));
				}
                   //为了保证异常订单正常工作, 除开下单待分配的退回   退回的时候把流程人员写进去
                   param.put("flowUserId", user.getId());
                   param.put("flowUserName", user.getRealName()+user.getLoginName());
                   param.put("flowUserOrgId", receicveMap.get("id"));
                   param.put("flowUserOrgName", receicveMap.get("name"));
			}
			param.put("waitingReceiverId", uId);
			param.put("waitingReceiverName", uName);
			param.put("waitingReceiverOrgId", deptId);
			param.put("waitingReceiverOrgName", deptName);
			param.put("updaterId", userEntity.getId());
			param.put("updaterName", userEntity.getRealName());
			param.put("updaterOrgId", userEntity.getOrgId());
			param.put("updaterOrgName", map.get("name"));
			param.put("updateTime", new Date());
			//最新备注时间
			param.put("lastRemarkTime", new Date());
			param.put("lastRemark", param.get("return_order_remark").toString());
			productOrderDao.goBack(param);
			//重新计算写入分配超期到超期表中
			if(!StringUtils.isEmpty(order.getFlowContent())) {
				ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
				//获取流程节点
				List<Node> nodelist = flowService.getNode(id);
				Node node = new Node();
				if (nodelist.size() > 0) {
					node = flowService.queyNodeListByName("分配", order.getId());
					if (null != node.getName()) {
						long currentTime = System.currentTimeMillis();
						Date date = new Date(currentTime);
						Integer hours = 0;
						timestatus.setNodeId(node.getId().toString());
						timestatus.setNodeName(node.getName());
						hours = node.getHandleDate();
						timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
						timestatus.setNodeStartTime(date);
						long millisecond = 0;
						long Days = (long) Math.ceil((double)node.getHandleDate() / 24);
						if (hours > 0) {
							millisecond = Days * 24 * 3600*1000;
						}
						Date currentDate = null;
						//获取当前节点的配置的计算出的超期时间
						currentDate = commonService.getDateFromStartByType(date,
								(int) Math.ceil((double)node.getHandleDate() / 24), millisecond,
								node.getIsNaturalorWorkday());
						currentDate = DateUtils.getDate(DateUtils.dateString(currentDate,"yyyy-MM-dd"),"yyyy-MM-dd");
						timestatus.setNodeEndTime(currentDate);
						timestatus.setNodeProcessTime((int) Math.ceil((double)hours / 24));
						timestatus.setNodeSuspendMillisecond(millisecond);
						timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
						productTimeStatusDao.updateTimeOutStatus(timestatus);
					}
				}
			}
			// 插入操作记录
			SystemRecord record = new SystemRecord();
			record.setId(DggKeyWorker.nextId());// id
			record.setSource("2");
			record.setWorkTableName("zzsc_product_order");
			record.setWorkId(order.getId());
			record.setWorkNo(order.getScProductOrderNo());
			record.setOperateType("23");
			record.setRemarks("订单退回" + param.get("return_order_remark").toString());
			systemRecordService.save(record, user);

			try {//退回发送消息 失败就算了
				//通过MQ推送消息到UC
				CustomerRecord customerRecord = new CustomerRecord();
				customerRecord.setCustomerId(order.getCustomerId());
				customerRecord.setTableName("zzsc_product_order");
				customerRecord.setTableId(order.getId());
				customerRecord.setTableNo(order.getScProductOrderNo());
				customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE10);
				customerRecord.setCreaterId(userEntity.getId());
				if (StringUtils.isNotEmpty(param.get("return_order_remark"))){
					customerRecord.setContent(param.get("return_order_remark").toString());
				}
				MQMessageSendUtil.ucMessageSend(customerRecord);
				//提交之后，将订单信息同步到企大顺生产中心
				MQMessageSendUtil.qdsMessageSend(order, null,  userEntity);
				if (commonStatus == 1) {// 分配待接收的退回   分配的生产订单{0}已经于{1}被退回，请及时确认处理！
					String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
					List<UserEntity> users = new ArrayList<>();
					UserEntity receiver = new UserEntity();
					receiver.setId(order.getAllotUserId());
					users.add(receiver);//接收人
					commonService.sendMsgByAsynchronous(users,msgs,"ZZSC_SC_ALLOT_GO_BACK");//分配退回模板
				} else if (commonStatus == 2) {//转单待接收的退回 转单的生产订单{0}已经于{1}被退回，请及时确认处理！
					String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
					List<UserEntity> users = new ArrayList<>();
					users.add(user);//接收人
					commonService.sendMsgByAsynchronous(users,msgs,"ZZSC_SC_SLIP_GO_BACK");//转单退回模板
				} else if (commonStatus == 3) {//移交待接收的退回 移交的生产订单{0}已经于{1}被退回，请及时确认处理！
					String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
					List<UserEntity> users = new ArrayList<>();
					users.add(user);//接收人
					commonService.sendMsgByAsynchronous(users,msgs,"ZZSC_SC_TURN_OVER_GO_BACK");//移交退回模板
				}
				String msgContent="您好，您的客户"+order.getCustomerName()+"订单"+order.getOrderNo()+"办理的"
						+order.getScProductOrderNo()+"业务，订单申请退单,请及时确认处理";
				commonService.sendQgjMessage(order.getOrderId(),order.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgContent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "success";
		} else {
			return "退回失败,提系统参数错误";
		}
	}
	/**
	 * 订单转单
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "unlikely-arg-type" })
	@Transactional
	public String transferOrder(Map param) {
//		Long id = Long.parseLong(param.get("ids").toString());
		String[] strings = param.get("ids").toString().split(",");
		for (String string : strings) {
			ProductOrder order = productOrderDao.selectByPrimaryKey(Long.valueOf(string));//当前订单
			UserEntity userEntity = sessionmanager.getCurrentUser();// 当前操作人
			Long uId = null;//转单前流程人员id

			String uName = "";//转单前流程人员name

			Long deptId = null;//转单前流程人员部门id

			String deptName = "";//转单前流程人员部门
			Long transferUserId = Long.parseLong(param.get("transferUserId").toString());
			if (userEntity.getId().equals(transferUserId)) {
				return "您不能转给自己";
			}
			if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
				if (!userEntity.getId().equals(order.getReceiverId())) {
					return "您无权操作,当前操作人不是接收人";
				}
				uId = order.getReceiverId();//接单人id
				uName = order.getReceiverName();//接单人
				deptId = order.getReceiverOrgId();
				deptName = order.getReceiverOrgName();
				order.setProductUserId(null);
				order.setProductUserName(null);
				order.setProductUserId(null);
				order.setProductOrgId(null);
			} else {
				if (!userEntity.getId().equals(order.getProductUserId())) {
					return "您无权操作,当前操作人不是接收人";
				}
				uId = order.getProductUserId();//负责人id
				uName = order.getProductUserName();//负责人
				deptId = order.getProductOrgId();
				deptName = order.getProductOrgName();
				order.setReceiverId(null);
				order.setReceiverName(null);
				order.setReceiverOrgId(null);
				order.setReceiverOrgName(null);
			}
			if (!order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_FPDJS)
					&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_ZDDJS)
					&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_YJDJS)
					&& !order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_TDDJS)
					&& !ScProductConstant.SC_ORDER_IN_PROCESS.equals(order.getStatus())
					&& !ScProductConstant.SC_ORDER_SUSPEND.equals(order.getStatus())) {
				// 如果当前状态不是分配待接收、转单待接收、转交待接收、移交待接收、办理中、暂停中
				return "当前订单状态已改变，不能进行转单";
			}
			Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());//当前操作人部门
			UserEntity transfer = userservice.findUserById(Long.parseLong(param.get("transferUserId").toString()));
			Map transfermap = this.commonMangerExtService.findOrg(transfer.getOrgId());//接收人部门
			param.put("status", ScProductConstant.SC_TO_RECEIVE_ZDDJS);//转单待接收
			if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
				param.put("receiverId", transfer.getId());
				param.put("receiverName", transfer.getRealName() + transfer.getLoginName());
				param.put("receiverOrgId", transfermap.get("id"));
				param.put("receiverOrgName", transfermap.get("name"));
			} else {// 分配给负责人
				param.put("receiverId", transfer.getId());
				param.put("receiverName", transfer.getRealName() + transfer.getLoginName());
				param.put("receiverOrgId", transfermap.get("id"));
				param.put("receiverOrgName", transfermap.get("name"));
				param.put("productUserId", transfer.getId());
				param.put("productUserName", transfer.getRealName() + transfer.getLoginName());
				param.put("productUserOrgId", transfermap.get("id"));
				param.put("productUserOrgName", transfermap.get("name"));
			}
			//流程人员改了
			param.put("flowUserId", transfer.getId());
			param.put("id", order.getId());
			param.put("flowUserName", transfer.getRealName() + transfer.getLoginName());
			param.put("flowUserOrgId", transfermap.get("id"));
			param.put("flowUserOrgName", transfermap.get("name"));
			param.put("waitingReceiverId", uId);
			param.put("waitingReceiverName", uName);
			param.put("waitingReceiverOrgId", deptId);
			param.put("waitingReceiverOrgName", deptName);
			param.put("updaterId", userEntity.getId());
			param.put("updaterName", userEntity.getRealName());
			param.put("updaterOrgId", userEntity.getOrgId());
			param.put("updaterOrgName", map.get("name"));
			param.put("updateTime", new Date());
			param.put("originCode", ScProductConstant.ORDER_SOURCE_SLIP);//资源来源转单
			//最新备注时间
			param.put("lastRemarkTime", new Date());
			param.put("lastRemark", param.get("transfer_order_remark").toString());
			productOrderDao.goBack(param);
			// 插入操作记录
			SystemRecord record = new SystemRecord();
			record.setId(DggKeyWorker.nextId());// id
			record.setSource("2");
			record.setWorkTableName("zzsc_product_order");
			record.setWorkId(order.getId());
			record.setWorkNo(order.getScProductOrderNo());
			record.setOperateType("24");
			record.setRemarks("订单转单:" + param.get("transfer_order_remark").toString());
			systemRecordService.save(record, transfer);
			try {// 发送消息 生产订单{0}已经于{1}转单给你，请及时确认处理！
				//通过MQ推送消息到UC
				CustomerRecord customerRecord = new CustomerRecord();
				customerRecord.setCustomerId(order.getCustomerId());
				customerRecord.setTableName("zzsc_product_order");
				customerRecord.setTableId(order.getId());
				customerRecord.setTableNo(order.getScProductOrderNo());
				customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE13);
				customerRecord.setCreaterId(userEntity.getId());
				if (StringUtils.isNotEmpty(param.get("transfer_order_remark"))) {
					customerRecord.setContent(param.get("transfer_order_remark").toString());
				}
				MQMessageSendUtil.ucMessageSend(customerRecord);

				//提交之后，将订单信息同步到企大顺生产中心
				MQMessageSendUtil.qdsMessageSend(order, null, userEntity);
				String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
				List<UserEntity> users = new ArrayList<>();
				users.add(transfer);//接收人
				commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_SLIP");//转单模板
				String msgConent = "您好，您的客户" + order.getCustomerName() + "订单" + order.getOrderNo() + "办理的" + order.getScProductOrderNo() + "业务，订单转单给" + transfer.getRealName() + ",请及时确认处理";
				commonService.sendQgjMessage(order.getOrderId(), order.getBusinessTypeCode(), userEntity.getId(), userEntity.getRealName(), userEntity.getLoginName(), msgConent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "success";
	}
	/**
	 * 订单移交
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public String devolveonOrder(Map param) {
		Long id = Long.parseLong(param.get("id").toString());
		ProductOrder order = productOrderDao.selectByPrimaryKey(id);//当前订单
		UserEntity userEntity = sessionmanager.getCurrentUser();// 当前操作人
		Long uId = null;//移交前流程人员id

		String uName = "";//移交前流程人员name

		Long deptId=null;//移交前流程人员部门id

		String deptName ="";//移交前流程人员部门
		ValidateUtils.isTrue(!ScProductConstant.SC_TO_RECEIVE_XDDJS.equals(order.getStatus()) &&
		!ScProductConstant.SC_ORDER_BACK_TO_ALLOT.equals(order.getStatus()),ProductOrderExcption.class,"待分配订单不能移交!");
		if(order.getAllotWay()==null){
			return "待分配订单退单不能移交!";
		}
		if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
			uId = order.getReceiverId();//接单人id
			uName = order.getReceiverName();//接单人
			deptId = order.getReceiverOrgId();
			deptName = order.getReceiverOrgName();
		}else {
			uId =order.getProductUserId();//负责人id
			uName = order.getProductUserName();//负责人
			deptId = order.getProductOrgId();
			deptName = order.getProductOrgName();
		}
		Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());//当前操作人部门
		UserEntity transfer = userservice.findUserById(Long.parseLong(param.get("devolveonUserId").toString()));
		Map transfermap = this.commonMangerExtService.findOrg(transfer.getOrgId());//接收人部门
		String status = order.getStatus();
		//只有办理中和待接收的移交之后需要改变状态
		if (ScProductConstant.SC_TO_RECEIVE_FPDJS.equals(status) || ScProductConstant.SC_TO_RECEIVE_ZDDJS.equals(status)
				|| ScProductConstant.SC_TO_RECEIVE_YJDJS.equals(status) || ScProductConstant.SC_TO_RECEIVE_TDDJS.equals(status)
				|| ScProductConstant.SC_ORDER_IN_PROCESS.equals(status)){
			param.put("status", ScProductConstant.SC_TO_RECEIVE_YJDJS);//移交待接收
		}else {//例如暂停  完结 结项这些需要流程人员
			param.put("status", order.getStatus());//移交待接收
		}
		param.put("flowUserId",transfer.getId());
		param.put("flowUserName",transfer.getRealName()+transfer.getLoginName());
		param.put("flowUserOrgId",transfermap.get("id"));
		param.put("flowUserOrgName",transfermap.get("name"));
		if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
			param.put("receiverId", transfer.getId());
			param.put("receiverName", transfer.getRealName()+transfer.getLoginName());
			param.put("receiverOrgId", transfermap.get("id"));
			param.put("receiverOrgName", transfermap.get("name"));
		} else {// 分配给负责人
			param.put("receiverId", transfer.getId());
			param.put("receiverName", transfer.getRealName()+transfer.getLoginName());
			param.put("receiverOrgId", transfermap.get("id"));
			param.put("receiverOrgName", transfermap.get("name"));
			param.put("productUserId", transfer.getId());
			param.put("productUserName", transfer.getRealName()+transfer.getLoginName());
			param.put("productUserOrgId", transfermap.get("id"));
			param.put("productUserOrgName", transfermap.get("name"));
		}
		param.put("waitingReceiverId", uId);
		param.put("waitingReceiverName", uName);
		param.put("waitingReceiverOrgId",deptId);
		param.put("waitingReceiverOrgName",deptName);
		param.put("updaterId", userEntity.getId());
		param.put("updaterName", userEntity.getRealName());
		param.put("updaterOrgId", userEntity.getOrgId());
		param.put("updaterOrgName", map.get("name"));
		param.put("updateTime", new Date());
		param.put("originCode", ScProductConstant.ORDER_SOURCE_TRANSFER);//资源来源转单
		productOrderDao.goBack(param);
		// 插入操作记录
		SystemRecord record = new SystemRecord();
		record.setId(DggKeyWorker.nextId());// id
		record.setSource("2");
		record.setWorkTableName("zzsc_product_order");
		record.setWorkId(order.getId());
		record.setWorkNo(order.getScProductOrderNo());
		record.setOperateType("26");
		record.setRemarks("订单移交:"+param.get("devolveon_order_remark").toString());
		systemRecordService.save(record, transfer);
		// 生产订单{0}已经于{1}移交给你，请及时确认处理！
		try {//不让影响其他功能,发送失败就算了
			String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
			List<UserEntity> users = new ArrayList<>();
			users.add(transfer);//接收人
			commonService.sendMsgByAsynchronous(users,msgs,"ZZSC_SC_TURN_OVER");//移交模板
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

}

